package com.jse.util.concurrent.old.synchronization;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

/**
 * 简单并发测试
 * @author zenghua233
 *
 */
public class CounterTest {
	private int i = 0;
	
	public synchronized void increment(String taskName) {
		i++;
	}
	
	@Test
	public void test() throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 1000000; i++) {
			executor.execute(new Task("thread-" + i));
		}
		executor.shutdown();
		Thread.sleep(1000);
		//如果没有加synchronized，最后的值小于1000000
		System.out.println(i);
	}
	
	class Task implements Runnable {
		String taskName;
		
		public Task(String taskName) {
			this.taskName = taskName;
		}
		
		@Override
		public void run() {
			increment(taskName);
		}
	}
}
